//
// Created by 23602 on 25-8-4.
//

#ifndef MEDUSA_HPP
#define MEDUSA_HPP
#include <SFML/Graphics.hpp>
#include <cmath>
#include <ctime>
#include <algorithm>
#include <vector>
// 线性插值函数
sf::Color interpolateColor(const sf::Color& start, const sf::Color& end, float t) {
    return sf::Color(
        static_cast<uint8_t>(start.r + t * (end.r - start.r)),
        static_cast<uint8_t>(start.g + t * (end.g - start.g)),
        static_cast<uint8_t>(start.b + t * (end.b - start.b))
    );
}
class Medusa {
public:
    Medusa(std::size_t particleCount)
        : N(particleCount), x(N), y(N), k(N), e(N), d(N), a(N) {
        for (std::size_t i = 0; i < N; ++i) {
            x[i] = i % 200;
            y[i] = i / 43.0;
            k[i] = 5.0 * std::cos(x[i] / 14.0) * std::cos(y[i] / 30.0);
            e[i] = y[i] / 8.0 - 13.0;
            d[i] = (k[i] * k[i] + e[i] * e[i]) / 59.0 + 4.0;
            a[i] = std::atan2(k[i], e[i]);
        }

        points.setPrimitiveType(sf::PrimitiveType::Points);
        points.resize(N);
        transform.scale({2.0, 2.0});
        states.transform = transform;
    }

    void update(double t) {
        // 起始和结束颜色
        t *= 0.8;
        sf::Color startColor(0, 0, 102);   // #000066
        sf::Color endColor(0, 255, 255, 128);   // #00FFFF
        for (std::size_t i = 0; i < N; ++i) {
            double q = 60.0 - 3.0 * std::sin(a[i] * e[i]) + k[i] * (3.0 + 4.0 / d[i] * std::sin(d[i] * d[i] - 2.0 * t));
            double c = d[i] / 2.0 + e[i] / 99.0 - t / 18.0;

            double px = q * std::sin(c) + 200;
            double py = (q + 9.0 * d[i]) * std::cos(c) + 200;

            points[i].position = sf::Vector2f(static_cast<float>(px), static_cast<float>(py));
            // points[i].color = sf::Color(255, 255, 255, 100);
            // float tt = static_cast<float>(i) / (N - 1);  // 0.0 到 1.0
            points[i].color = sf::Color(255, 255, 255, 100);
        }

    }

    void draw(sf::RenderTarget& target) const {
        target.draw(points, transform);
    }

private:
    std::size_t N;
    std::vector<double> x, y, k, e, d, a;
    sf::VertexArray points;
    sf::Transform transform;
    sf::RenderStates states;
};
#endif //MEDUSA_HPP
